package com.fire.control.system.module.warning.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fire.control.system.config.getui.GetuiManager;
import com.fire.control.system.config.socketIo.SocketIoMessageEventHandler;
import com.fire.control.system.dto.DeviceDTO;
import com.fire.control.system.dto.GetuiDto;
import com.fire.control.system.dto.MessageUserDto;
import com.fire.control.system.dto.MqttDev;
import com.fire.control.system.dto.MsgPushSetDTO;
import com.fire.control.system.dto.SmsDto;
import com.fire.control.system.dto.UnsolvedListDTO;
import com.fire.control.system.dto.UserDTO;
import com.fire.control.system.dto.WarningInfoDto;
import com.fire.control.system.entity.Company;
import com.fire.control.system.entity.MessagePushSet;
import com.fire.control.system.entity.Role;
import com.fire.control.system.entity.WarningInfo;
import com.fire.control.system.entity.WarningInfoHistory;
import com.fire.control.system.entity.WarningLevel;
import com.fire.control.system.entity.WarningMessageDetail;
import com.fire.control.system.entity.WarningProtocol;
import com.fire.control.system.module.company.dao.CompanyMapper;
import com.fire.control.system.module.company.service.CompanyService;
import com.fire.control.system.module.device.dao.DeviceMapper;
import com.fire.control.system.module.device.service.DeviceService;
import com.fire.control.system.module.role.dao.RoleMapper;
import com.fire.control.system.module.user.dao.UserMapper;
import com.fire.control.system.module.warning.dao.MessagePushSetMapper;
import com.fire.control.system.module.warning.dao.MessagePushSetRepository;
import com.fire.control.system.module.warning.dao.WarningInfoMapper;
import com.fire.control.system.module.warning.dao.WarningLevelRepository;
import com.fire.control.system.module.warning.dao.WarningMapper;
import com.fire.control.system.module.warning.dao.WarningMessageDetailMapper;
import com.fire.control.system.module.warning.service.WarningProtocolService;
import com.fire.control.system.module.warning.service.WarningService;
import com.fire.control.system.statics.ResponseMessage;
import com.fire.control.system.statics.Status_Message;
import com.fire.control.system.statics.Status_Online;
import com.fire.control.system.statics.Status_Warning;
import com.fire.control.system.statics.Type_MessageTarget;
import com.fire.control.system.statics.Type_MsgScope;
import com.fire.control.system.statics.Type_SureWarning;
import com.fire.control.system.statics.Type_Warning;
import com.fire.control.system.support.protocol.comman.ProtocolSelector;
import com.fire.control.system.support.protocol.comman.ResponseProtocol;
import com.fire.control.system.support.protocol.device.DeviceRequestProtocol;
import com.fire.control.system.support.util.ResultPageUtil;
import com.fire.control.system.support.util.SmsUtil;
import com.fire.control.system.support.util.XdaoDate;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 
 * @ClassName:  WarningServiceImpl
 * @Description:  报警设备业务接口具体实现
 * @author:  xiechengguang
 * @date:  2017年5月12日 下午6:23:25
 *
 */
@Service
public class WarningServiceImpl implements WarningService {
	
	private static final Logger logger = LoggerFactory.getLogger(WarningServiceImpl.class);
	
	@Autowired private WarningLevelRepository warningLevelRepository;
	@Autowired private MessagePushSetRepository messagePushSetRepository;
	@Autowired private ProtocolSelector protocolSelector;
	@Autowired private DeviceService deviceService;
	@Autowired private WarningMapper warningMapper;
	@Autowired private MessagePushSetMapper messagePushSetMapper;
	@Autowired private WarningProtocolService warningProtocolService;
	@Autowired private UserMapper userMapper;
	@Autowired private WarningInfoMapper warningInfoMapper;
	@Autowired private SmsUtil loginUtil;
	@Autowired private WarningMessageDetailMapper warningMessageDetailMapper;
	@Autowired private GetuiManager getuiManager;
	@Autowired private CompanyMapper companyMapper;
	@Autowired private RoleMapper roleMapper;
	@Autowired private SocketIoMessageEventHandler socketIoMessageEventHandler;
	@Autowired private DeviceMapper deviceMapper;
	@Autowired private CompanyService companyService;
	
	
	/**
	 * <p>Title: getSolvedWarnings</p> 
	 * <p>Description: 已完成处理报警设备列表  </p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#getWarningList(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol getSolvedWarnings(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		PageHelper.startPage(page, size);
		String companyId = user.getCompany().getId();
		List<UnsolvedListDTO> solvedList = warningInfoMapper.getSolvedList(companyId);
		
		if(solvedList != null && !solvedList.isEmpty()) {
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			respProtocol.setData(ResultPageUtil.resultPage(new PageInfo<UnsolvedListDTO>(solvedList), solvedList));
			return respProtocol;
		}
		ResponseMessage.CODE_204.messageToProtocol(respProtocol);
		return respProtocol;
	}
	
	
	/**
	 * <p>Title: deleteSolvedWarning</p> 
	 * <p>Description: 删除已完成处理报警设备信息  </p> 
	 * <p>删除，实际上是将status改为false</p>
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#deleteWarning(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol deleteSolvedWarning(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String[] ids = requestProtocol.getIds();
		if(null != ids && ids.length > 0) {
			int n = 0;
			for(String id : ids) {
				int i = warningInfoMapper.updateWarningInfoStatus(id);
				n = n + i;
			}
			if(n == ids.length) {
				ResponseMessage.CODE_200.messageToProtocol(respProtocol);
				respProtocol.setDate(new XdaoDate());
				return respProtocol;
			}
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * <p>Title: searchSolvedWarnings</p> 
	 * <p>Description: 按条件搜索已完成处理报警设备列表</p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#searchWarnings(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol searchSolvedWarnings(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		
		List<String> companyIds = this.companyService.getChildCompanyIdList(user.getCompany().getId());
		requestProtocol.setCompanyIds(companyIds);
		
		PageHelper.startPage(page, size);
		List<UnsolvedListDTO> list = warningInfoMapper.searchSolvedWarnings(requestProtocol);
		if(list != null && !list.isEmpty()) {
			for(UnsolvedListDTO dto : list) {
				if(dto != null) {
					dto.setSureWarningType(Type_SureWarning.getValue(dto.getSureWarningType()));
				}
			}
			respProtocol.setData(ResultPageUtil.resultPage(new PageInfo<UnsolvedListDTO>(list), list));
			return respProtocol;
		}
		ResponseMessage.CODE_204.messageToProtocol(respProtocol);
		return respProtocol;
	}
	
	/**
	 * <p>Title: getUnsolvedWarnings</p> 
	 * <p>Description: 待处理报警设备列表</p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#getUnsolvedWarnings(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol getUnsolvedWarnings(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		PageHelper.startPage(page, size);
		String companyId = user.getCompany().getId();
		List<UnsolvedListDTO> unsolvedList = warningInfoMapper.getUnsolvedList(companyId);
		
		if(unsolvedList != null && !unsolvedList.isEmpty()) {
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			respProtocol.setData(ResultPageUtil.resultPage(new PageInfo<UnsolvedListDTO>(unsolvedList), unsolvedList));
			return respProtocol;
		}
		ResponseMessage.CODE_204.messageToProtocol(respProtocol);
		return respProtocol;
		
	}
	
	/**
	 * <p>Title: ignoreWarning</p> 
	 * <p>Description: 忽略误报 报警设备信息  </p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#ignoreWarning(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol ignoreWarning(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String[] ids = requestProtocol.getIds();
		if(null != ids && ids.length > 0) {
			int n = 0;
			for(String id : ids) {
				//wanbo 注释
				/*int i = warningInfoRepository.ignoreWarning(id);
				n = n + i;*/
			}
			if(n == ids.length) {
				respProtocol.setCode(0);
				respProtocol.setMessage("success");
				return respProtocol;
			}
		}
		respProtocol.setCode(-1);
		respProtocol.setMessage("fail");
		return respProtocol;
	}
	
	/**
	 * <p>Title: searchUnsolvedWarnings</p> 
	 * <p>Description: 按条件搜索未处理的报警设备列表  </p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#searchUnsolvedWarnings(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol searchUnsolvedWarnings(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		
		List<String> companyIds = this.companyService.getChildCompanyIdList(user.getCompany().getId());
		requestProtocol.setCompanyIds(companyIds);
		
		PageHelper.startPage(page, size);
		List<UnsolvedListDTO> list = warningInfoMapper.searchUnsolvedWarnings(requestProtocol);
		if(list != null && !list.isEmpty()) {
			for(UnsolvedListDTO dto : list) {
				if(dto != null) {
					dto.setSureWarningType(Type_SureWarning.getValue(dto.getSureWarningType()));
				}
			}
			respProtocol.setData(ResultPageUtil.resultPage(new PageInfo<UnsolvedListDTO>(list), list));
			return respProtocol;
		}
		ResponseMessage.CODE_204.messageToProtocol(respProtocol);
		return respProtocol;
	}
	
	/**
	 * <p>Title: getWarningModeList</p> 
	 * <p>Description: 报警模式设置列表</p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#getWarningModeList(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol getWarningModeList(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		
		List<WarningLevel> warningModeList =  warningLevelRepository.getWarningLevelList();
		if(warningModeList != null) {
			respProtocol.setData(warningModeList);
			respProtocol.setCode(0);
			respProtocol.setMessage("success");
			return respProtocol;
		}
		respProtocol.setCode(-1);
		respProtocol.setMessage("fail");
		return respProtocol;
	}
	/**
	 * <p>Title: deleteWarningMode</p> 
	 * <p>Description: 删除报警模式设置信息</p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#deleteWarningMode(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol deleteWarningMode(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String[] ids = requestProtocol.getIds();
		if(null != ids && ids.length > 0) {
			int n = 0;
			for(String id : ids) {
				int i = warningLevelRepository.updateWarningLevelStatus(id);
				n = n + i;
			}
			if(n == ids.length) {
				respProtocol.setCode(0);
				respProtocol.setMessage("success");
				return respProtocol;
			}
		}
		respProtocol.setCode(-1);
		respProtocol.setMessage("fail");
		return respProtocol;
	}
	
	/**
	 * <p>Title: updateWarningMode</p> 
	 * <p>Description: 修改报警模式设置信息  </p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#updateWarningMode(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol updateWarningMode(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String id = requestProtocol.getId();
		if(id != null) {
			WarningLevel warningLevel = warningLevelRepository.findOne(id);
			if(warningLevel != null) {
				if(requestProtocol.getLevel() != null) {
					warningLevel.setLevel(requestProtocol.getLevel());
				}
				if(requestProtocol.getLevelDesc() != null) {
					warningLevel.setLevelDesc(requestProtocol.getLevelDesc());
				}
				if(requestProtocol.getLevelName() != null) {
					warningLevel.setLevelName(requestProtocol.getLevelName());
				}
				if(requestProtocol.getTimeSet() != null) {
					warningLevel.setTimeSet(requestProtocol.getTimeSet());
				}
				
				warningLevel.setCreateTime(new Date());
				WarningLevel returned = warningLevelRepository.save(warningLevel);
				if(returned != null) {
					respProtocol.setCode(0);
					respProtocol.setMessage("success");
					return respProtocol;
				}
			}
		}
		respProtocol.setCode(-1);
		respProtocol.setMessage("fail");
		return respProtocol;
	}
	
	/**
	 * <p>Title: addWarningMode</p> 
	 * <p>Description: 新增报警模式设置信息 </p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#addWarningMode(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol addWarningMode(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		WarningLevel warningLevel = new WarningLevel();
		warningLevel.setId(requestProtocol.getId());
		warningLevel.setLevel(requestProtocol.getLevel());
		warningLevel.setLevelDesc(requestProtocol.getLevelDesc());
		warningLevel.setLevelName(requestProtocol.getLevelName());
		warningLevel.setTimeSet(requestProtocol.getTimeSet());
		warningLevel.setStatus(true);
		
		WarningLevel returned = warningLevelRepository.save(warningLevel);
		if(returned != null) {
			respProtocol.setCode(0);
			respProtocol.setMessage("success");
			return respProtocol;
		}
		respProtocol.setCode(-1);
		respProtocol.setMessage("fail");
		return respProtocol;
	}
	/**
	 * <p>Title: getMsgPushList</p> 
	 * <p>Description: 报警推送设置列表</p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#getMsgPushList(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol getMsgPushList(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		
		String companyId = user.getCompany().getId();
		List<MsgPushSetDTO> msgPushList =  messagePushSetMapper.getMsgPushSetList(companyId);
		if(msgPushList != null && !msgPushList.isEmpty()) {
			for(MsgPushSetDTO dto : msgPushList) {
				String id = dto.getId();
				List<String> roleNames = roleMapper.getUsersByMsgPushId(id);
				StringBuffer sb = new StringBuffer();
				if(roleNames != null && roleNames.size() == 3) {
					dto.setSendObject("所有人");
				} else {
					for(String roleName : roleNames) {
						sb.append(roleName);
						sb.append(",");
					}
					dto.setSendObject(sb.toString().substring(0,sb.toString().length()-1));
				}
			}
			respProtocol.setData(msgPushList);
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			return respProtocol;
		}
		ResponseMessage.CODE_204.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	/**
	 * <p>Title: deleteMsgPushSet</p> 
	 * <p>Description: 删除报警推送设置信息  </p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#deleteMsgPushSet(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol deleteMsgPushSet(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String[] ids = requestProtocol.getIds();
		if(null != ids && ids.length > 0) {
			int n = 0;
			for(String id : ids) {
				int i = messagePushSetMapper.deleteMessagePushSet(id);
				n = n + i;
			}
			if(n == ids.length) {
				ResponseMessage.CODE_200.messageToProtocol(respProtocol);
				respProtocol.setDate(new XdaoDate());
				return respProtocol;
			}
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	/**
	 * <p>Title: addMsgPushSet</p> 
	 * <p>Description: 新增报警推送设置信息</p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#addMsgPushSet(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Transactional
	@Override
	public ResponseProtocol addMsgPushSet(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String companyId = user.getCompany().getId();
		requestProtocol.setCompanyId(companyId);
		MessagePushSet messagePushSet = new MessagePushSet();
		messagePushSet = this.setMessagePushSet(messagePushSet, requestProtocol);
		
		String[] ids = requestProtocol.getIds();
		List<Role> roles = new ArrayList<Role>();
		for(String roleId : ids) {
			Role role = roleMapper.findById(roleId);
			roles.add(role);
			// 保存报警推送-角色关系
			String id = messagePushSet.getId();
			messagePushSetMapper.saveMsgPushSetAndRoleRelation(id, roleId);
		}
		
		messagePushSet.setRoles(roles);
		
		MessagePushSet returned = messagePushSetRepository.save(messagePushSet);
		ResponseMessage.CODE_200.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
		
	}
	
	/**
	 * <p>Author: xiechengguang</p> 
	 * <p>Title: addDefaultMsgPushSet</p> 
	 * <p>Description: 添加默认报警推送设置信息  </p> 
	 * @param requestProtocol
	 * @param user
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#addDefaultMsgPushSet(com.fire.control.system.support.protocol.device.DeviceRequestProtocol, com.fire.control.system.dto.UserDTO)
	 */
	@Transactional
	@Override
	public void addDefaultMsgPushSet(String companyId) {
		for(Type_Warning type : Type_Warning.values()) {
			String name = type.name();
			MessagePushSet messagePushSet = new MessagePushSet();
			messagePushSet.setWarningType(name);
			messagePushSet.setMsgScopeType(Type_MsgScope.valueOf("deviceGroup"));
			messagePushSet.setSendApp(true);
			messagePushSet.setSendSms(true);
			messagePushSet.setSendDeviceAddress(true);
			messagePushSet.setSendWarningType(true);
			
			Company company = companyMapper.getById(companyId);
			messagePushSet.setCompany(company);
			
			String[] ids = {"anquanguanliyuan"};
			List<Role> roles = new ArrayList<Role>();
			for(String roleId : ids) {
				Role role = roleMapper.findById(roleId);
				roles.add(role);
				// 保存报警推送-角色关系
				String id = messagePushSet.getId();
				messagePushSetMapper.saveMsgPushSetAndRoleRelation(id, roleId);
			}
			messagePushSet.setRoles(roles);
			MessagePushSet returned = messagePushSetRepository.save(messagePushSet);
		}
		
	}
	
	
	
	/**
	 * @author: xiechengguang 
	 * @Title: setMessagePushSet   
	 * @Description: 添加/修改推送设置公共方法  
	 * @param:        
	 * @return: MessagePushSet      
	 * @throws
	 */
	public MessagePushSet setMessagePushSet(MessagePushSet messagePushSet, DeviceRequestProtocol requestProtocol) {
		
		messagePushSet.setMsgScopeType(Type_MsgScope.valueOf(requestProtocol.getMsgScopeType()));
		messagePushSet.setSendApp(requestProtocol.getSendApp());
		messagePushSet.setSendSms(requestProtocol.getSendSms());
		messagePushSet.setSendDeviceAddress(requestProtocol.getSendDeviceAddress());
		messagePushSet.setSendWarningType(requestProtocol.getSendWarningType());
		
		Company company = companyMapper.getById(requestProtocol.getCompanyId());
		messagePushSet.setCompany(company);
		messagePushSet.setWarningType(requestProtocol.getWarningType());
		
		return messagePushSet;
	}
	
	
	/**
	 * <p>Title: updateMsgPushSet</p> 
	 * <p>Description: 修改报警推送设置信息  </p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#updateMsgPushSet(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Transactional
	@Override
	public ResponseProtocol updateMsgPushSet(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		
		String id = requestProtocol.getId();
		MessagePushSet messagePushSet = messagePushSetMapper.findById(id);
		
		String companyId = user.getCompany().getId();
		requestProtocol.setCompanyId(companyId);
		
		if(messagePushSet !=null) {
			String[] ids = requestProtocol.getIds();
			List<Role> roles = new ArrayList<Role>();
			for(String roleId : ids) {
				Role role = roleMapper.findById(roleId);
				roles.add(role);
				// 先删除原来的 报警推送-角色关系
				messagePushSetMapper.deleteMsgPushSetAndRoleRelation(id, roleId);
				// 保存新的 报警推送-角色关系
				messagePushSetMapper.saveMsgPushSetAndRoleRelation(id, roleId);
			}
			messagePushSet = setMessagePushSet(messagePushSet, requestProtocol);
			
			int i = messagePushSetMapper.updateMessagePushSet(messagePushSet);
			if(i > 0) {
				ResponseMessage.CODE_200.messageToProtocol(respProtocol);
				respProtocol.setDate(new XdaoDate());
				return respProtocol;
			}
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	
	/**
	* @Title: manualSend
	* @Description: TODO(手动推送报警信息)
	* @author wanbo
	* @date  2017年6月30日 下午5:45:46
	* @param companyId
	* @param warningId
	*/
	@Transactional
	public void manualSend(String warningId){
		WarningInfoDto info = warningMapper.findWarningInfoDtoById(warningId);
		MessagePushSet msgSet = messagePushSetMapper.getMessagePushSet(info.getCompanyId(),info.getWarningType());
		List<Object> msgSetRoles = messagePushSetMapper.getMessageRoles(msgSet.getId());
		List<MessageUserDto> userDtos = userMapper.getWarningMsgUserList(msgSet.getMsgScopeType().toString(), info.getCompanyId(), info.getTargetDeviceId(), msgSetRoles);
		
		for (MessageUserDto msgUserDto : userDtos) {
			
			String userId = msgUserDto.getUserId();
			String phone = msgUserDto.getTel();
			String cid = msgUserDto.getCid();
			
			//消息明细记录
			WarningMessageDetail messageDetail = new WarningMessageDetail();
			messageDetail.setWarningId(info.getId());
			messageDetail.setTitle(Type_Warning.getText(info.getWarningType()));
			messageDetail.setContent(info.getAddress() + info.getWarningDesc());
			messageDetail.setUserId(msgUserDto.getUserId());
			
			//发送短信
			if (msgSet.isSendSms() && StringUtils.isNotEmpty(phone) && phone.length()==11) {
				//调用短信发送
				SmsDto smsDto = loginUtil.sendSmsWarning(phone, messageDetail.getContent());
				//记录明细
				messageDetail.setSendStatus(smsDto.getCode().equals("0")?Status_Message.success.toString():Status_Message.fail.toString());
				messageDetail.setClientType(Type_MessageTarget.sms.toString());
				messageDetail.setMsg(smsDto.getMsg());
				warningMessageDetailMapper.addWarningMessageDetail(messageDetail);
				logger.info("--->已发送短信消息");
			}
			
			//发送APP
			if(msgSet.isSendApp() && StringUtils.isNotEmpty(cid)){
				//调用个推
				GetuiDto getuiDto = getuiManager.pushNotificationSingle(messageDetail.getTitle(), messageDetail.getContent(), cid);
				//记录明细
				messageDetail.setSendStatus(getuiDto.getResult().equals("ok")?Status_Message.success.toString():Status_Message.fail.toString());
				messageDetail.setGetuiTaskId(getuiDto.getTaskId());
				messageDetail.setMsg(getuiDto.getMsg());
				messageDetail.setClientType(Type_MessageTarget.app.toString());
				warningMessageDetailMapper.addWarningMessageDetail(messageDetail);
				logger.info("--->已推送APP消息");
			}
			
			//推送 web消息
			{
				socketIoMessageEventHandler.send(userId, messageDetail.getContent());
				logger.info("--->已推送web消息");
			}
		}
	}
	
	public void deviceConnectSucceed(MqttDev dev){
		DeviceDTO device = deviceService.getBydevEUI(dev.getDevEUI());
		if(device==null){
			return;
		}
		//修改设备状态为正常 ?
		//deviceMapper.updateDeviceOnlineStatus(device.getId(), Status_Online.normal.toString());
		//修改报警信息为完成 ?
	}
	
	
	@Transactional
	@Override
	public void changeWarningProtocol(String devEUI,String fPort,String warningType,Date startTime,String warningDesc,String msg){
		DeviceDTO device = deviceService.getBydevEUI(devEUI);
		if(device==null){
			logger.info("--->此节点在系统里没有对应的设备devEUI:"+devEUI);
			return;
		}
		String deviceId = device.getId();
		WarningProtocol warningProtocol = warningProtocolService.getWarningProtocolByFport(fPort);
		String onlineStatus = warningProtocol.getWarningType().equals(Type_Warning.fire_alarm.toString())?Status_Online.alarm.toString():Status_Online.fault.toString();
		insertWarning(deviceId, onlineStatus, warningType, warningDesc, startTime, msg);
	}
	
	@Transactional
	@Override
	public void insertWarning(String deviceId,String onlineStatus,String warningType,String warningDesc,Date warningTime,String mqttMsg){
		DeviceDTO device = deviceService.getBydevId(deviceId);
		WarningInfo info = warningMapper.getWarningInfoLastNotComplete(device.getId(), warningType);
		
		//如果没有未完成状态的报警则此次报警是新的一次报警
		if(info==null){
			
			//修改设备在线状态
			deviceMapper.updateDeviceOnlineStatus(device.getId(), onlineStatus);
			logger.info("---->已修改设备状态deviceId:"+device.getId() +" onlineStatus:"+onlineStatus);
			
			info = new WarningInfo();
			info.setCompanyId(device.getCompanyId());
			info.setAddress(device.getMergerName()+device.getAddress());
			info.setStartTime(warningTime);
			info.setTargetDeviceId(device.getId());
			info.setWarningType(warningType);
			info.setCurrentStatusVal(Status_Warning.alarm.toString());
			info.setWarningDesc(warningDesc);
			warningInfoMapper.insertWarningInfo(info);
			logger.info("---->已记录为一次新的报警warningId:"+info.getId()+" warningType:"+warningType);
			
			//新的一次报警做一次消息推送
			//根据报警推送设置 推送对应内容
			manualSend(info.getId());
			
		}else{
			//是否更新报警时间?
			logger.info("---->此设备已有相同报警类型的报警信息了 deviceId:"+device.getId()+" warningType:"+warningType);
		}
		//无论是否为新的一次报警,都要记录报警历史记录
		WarningInfoHistory history = new WarningInfoHistory();
		history.setWarningId(info.getId());
		history.setDeviceId(device.getId());
		history.setAddress(info.getAddress());
		history.setStartTime(warningTime);
		history.setWarningType(warningType);
		history.setMqttMsg(mqttMsg);
		warningMapper.insertWarningInfoHistory(history);
		logger.info("---->已记录报警历史记录warningId:"+info.getId()+" deviceId:"+device.getId()+ " warningType:"+warningType);
	}
	
	/**
	 * <p>Author: xiechengguang</p> 
	 * <p>Title: getMsgPushSetById</p> 
	 * <p>Description: 获取报警推送信息</p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.warning.service.WarningService#getMsgPushSetById(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol getMsgPushSetById(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		
		String id = requestProtocol.getId();
		if(id != null) {
			MsgPushSetDTO msgPushSet = messagePushSetMapper.getById(id);
			String mpsid = msgPushSet.getId();
			List<String> roleNames = roleMapper.getUsersByMsgPushId(mpsid);
			StringBuffer sb = new StringBuffer();
			if(roleNames != null && roleNames.size() == 3) {
				msgPushSet.setSendObject("所有人");
			} else {
				for(String roleName : roleNames) {
					sb.append(roleName);
					sb.append(",");
				}
				msgPushSet.setSendObject(sb.toString().substring(0,sb.toString().length()-1));
			}
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			respProtocol.setData(msgPushSet);
			return respProtocol;
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}

	/**
	 * @author: xiechengguang 
	 * @Title: applyforMaintence   
	 * @Description: 维保申请（使用单位）   
	 * @param:        
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol applyforMaintence(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String companyId = user.getCompany().getId();
		String[] ids = requestProtocol.getIds();
		if(ids != null && ids.length > 0) {
			warningInfoMapper.applyforMaintence(companyId, ids);
			
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			return respProtocol;
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}

	/**
	 * @author: xiechengguang 
	 * @Title: manualSendWarnings   
	 * @Description: 手动报警推送 （批量） 
	 */
	@Override
	public ResponseProtocol manualSendWarnings(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String[] ids = requestProtocol.getIds();
		if(ids != null && ids.length > 0) {
			for(String warningId : ids) {
				this.manualSend(warningId); 
			}
			
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			return respProtocol;
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}

	
	
	
	

}
